package ${packageService};

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import ${packageDao}.${className}DAO;
import ${entityClass};

import java.util.Optional;

@Service
@Transactional
public class ${serivceName}Impl implements ${serivceName} {
	@Autowired
	private ${className}DAO ${className?lower_case}DAO;

	public void add${className}(${className} ${className?lower_case}) {

    <#list properties as pro>
      <#if pro.notnull>
      <#if pro.type == "String">
    if (!StringUtils.hasText(${className?lower_case}.get${pro.name?cap_first}())) {
			throw new RuntimeException("${pro.descript!''}不能为空！");
		}
      <#else>
    if (${className?lower_case}.get${pro.name?cap_first}() == null) {
			throw new RuntimeException("${pro.descript!''}不能为空！");
		}
      </#if>
      </#if>
    </#list>
		
		${className?lower_case}DAO.save(${className?lower_case});
		
	}

	// 删除
	public void delete${className}s(Integer[] ids) {
		if (ids.length == 0) {
			throw new RuntimeException("未选择删除对象");
		}
		for (Integer id : ids) {
			if (${className?lower_case}DAO.existsById(id)) {
				${className?lower_case}DAO.deleteById(id);
			} else {
				throw new RuntimeException(String.format("ID为：%d的记录未找到", id));
			}
		}
	}

	// 修改
	public void update${className}(${className} ${className?lower_case}) {
		Optional<${className}> o = ${className?lower_case}DAO.findById(${className?lower_case}.getId());
		if (!o.isPresent()) {
			throw new RuntimeException("ID不存在");
		}
		//唯一性判断
    /*
    * 
    */
		${className?lower_case}DAO.save(${className?lower_case});
	}

	// 分页模糊查询
	public Page<${className}> findAll(int page, int size, ${className} ${className?lower_case}) {
		ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreNullValues()
    <#list properties as p>
    <#if p.type == "String">
    .withMatcher("${p.name}",ExampleMatcher.GenericPropertyMatchers.contains())
    </#if>
    </#list>
    ;
		Example<${className}> example = Example.of(${className?lower_case}, matcher);
		Pageable pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.ASC, "id"));
		return ${className?lower_case}DAO.findAll(example, pageable);
	}
}
